package com.info.utils;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Timer;

import org.apache.log4j.Logger;
import org.net.operation.TerServer;

import com.info.server.StartServer;

/**
 * @author HAHA
 * 
 */
public class InfoPacket {
	private static Logger logger = Logger.getLogger(InfoPacket.class);
	private String uname = "";
	public long updateTime = 0L;
	public long createTime = 0L;
	public static final String UNKNOWN = "UNKNOWN";
	private ArrayList Msg_Str;
	private int MsgCount;
	private byte[] LastMsg;
	private int lastIndex = 0;

	Charset charset = null;
	CharsetDecoder decoder = null;
	private ByteBuffer byteBuffer = null;

	private String channelType = "UNKNOWN";
	private String channelId = null;
	private SocketChannel sc;
	private Selector selector;
	private Timer timer = null;

	private static SimpleDateFormat dateFormat = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");
	private static SimpleDateFormat fileFormat = new SimpleDateFormat(
			"yyyy-MM-dd");
	private static String filename = "";
	private ByteBuffer bufferOutput;
	private byte simiByte = 0;
	private int isStart = 0;
	private StringBuffer pendingStr = new StringBuffer("");

	public String getType() {
		return this.channelType;
	}

	public void setType(String type) {
		this.channelType = type;
	}

	public String getId() {
		return this.channelId;
	}

	public void setId(String id) {
		this.channelId = id;
	}

	public SocketChannel getChannel() {
		return this.sc;
	}

	public Selector getSelector() {
		return this.selector;
	}

	public void setChannel(SocketChannel channel) {
		this.sc = channel;
	}

	public void setSelector(Selector selector) {
		this.selector = selector;
	}

	public void setSecurity(Selector selctor, SocketChannel sc) {
		setChannel(sc);
		setSelector(this.selector);
	}

	public InfoPacket() {
		this.Msg_Str = new ArrayList();
		this.LastMsg = new byte[StartServer.GATE_RECV_BUFFER];
		this.MsgCount = 0;
		this.charset = Charset.forName(StartServer.gate_code);
		this.decoder = this.charset.newDecoder();
		this.byteBuffer = ByteBuffer.allocate(StartServer.GATE_RECV_BUFFER);
		this.bufferOutput = ByteBuffer
				.allocateDirect(StartServer.GATE_RECV_BUFFER + 1);
	}

	public String uppacket(ByteBuffer buffer) throws Exception {
		String str = "";
		if (this.bufferOutput == null)
			return str;
		buffer.flip();

		int i = buffer.limit() - 1;
		int j = 0;

		while (i >= 0) {
			byte aByte = buffer.get(i);
			if ((aByte & 0x80) != 128)
				break;
			i--;
			j++;
		}
		this.bufferOutput.clear();
		if (this.simiByte != 0) {
			this.bufferOutput.put(this.simiByte);
		}
		buffer.rewind();
		if (j % 2 == 0) {
			this.bufferOutput.put(buffer);
			this.simiByte = 0;
		} else {
			this.simiByte = buffer.get(buffer.limit() - 1);
			buffer.position(0);
			buffer.limit(buffer.limit() - 1);
			this.bufferOutput.put(buffer);
		}

		this.bufferOutput.flip();
		byte[] tempBytes = new byte[this.bufferOutput.limit()];
		this.bufferOutput.get(tempBytes);
		if (StartServer.DEBUG.equals("0")) {
			str = Byte2Hex.Bytes2HexString(tempBytes);
		} else {
			str = new String(tempBytes);
		}
		logger.info("SHW#原始数据" + str);
		return str;
	}

	public void extPacket(String packet_str) {
		// StringBuffer packetStr = new StringBuffer(packet_str);
		//
		// this.Msg_Str.clear();
		// this.Msg_Str.add(packet_str);// }
		StringBuffer packetStr = new StringBuffer(packet_str);
		if (packetStr.indexOf(StartServer.MSG_START_FLAG) > -1) {
			String terID = packetStr.substring(6, 18);
			if (!TerServer.terList.contains(terID)) {
				terID = packetStr.substring(10, 22);
				if (!TerServer.terList.contains(terID)) {
				logger.info("SHW#终端:" + terID + "的ID未注册,关闭连接");
				this.closeChannel();
				return;}
			}
		}
		this.Msg_Str.clear();
		while (packetStr.length() > 0)
			if (this.isStart == 1) {
				int endIndex = packetStr.indexOf(StartServer.MSG_END_FLAG);
				if (endIndex < 0)
					break;
				if (endIndex != packetStr.length()) {
					endIndex = packetStr.indexOf(StartServer.MSG_END_FLAG
							+ StartServer.MSG_START_FLAG);
					if (endIndex < 0) {
						endIndex = packetStr.length();
						String pstr = new String(
								this.pendingStr.append(packetStr.substring(0,
										endIndex)));
						this.Msg_Str.add(pstr);
						logger.info("SHW#原始数据截取" + pstr);
						packetStr.delete(0, endIndex);
						this.pendingStr.delete(0, this.pendingStr.length());
						this.isStart = 0;
					} else {
						String pstr = new String(
								this.pendingStr.append(packetStr.substring(0,
										endIndex + 4)));
						this.Msg_Str.add(pstr);
						logger.info("SHW#原始数据截取" + pstr);
						packetStr.delete(0, endIndex + 4);
						this.pendingStr.delete(0, this.pendingStr.length());
						this.isStart = 0;
					}

				} else {
					String pstr = new String(this.pendingStr.append(packetStr
							.substring(0, endIndex + 4)));
					this.Msg_Str.add(pstr);
					logger.info("SHW#原始数据截取" + pstr);
					packetStr.delete(0, endIndex + 4);
					this.pendingStr.delete(0, this.pendingStr.length());
					this.isStart = 0;
				}

			} else {
				int nextStartIndex = packetStr
						.indexOf(StartServer.MSG_START_FLAG);
				if (nextStartIndex <= -1)
					break;
				this.isStart = 1;
				// packetStr.delete(0, nextStartIndex + 1);

			}
	}

	public String decode(ByteBuffer byteBuffer) throws Exception {
		CharBuffer charBuffer = this.decoder.decode(byteBuffer);
		String result = charBuffer.toString();

		return result;
	}

	public ArrayList getMsg_Str() {
		return this.Msg_Str;
	}

	public int getMsgCount() {
		return this.MsgCount;
	}

	public void clear() {
		try {
			this.Msg_Str.clear();
			this.LastMsg = null;
			if (this.byteBuffer != null)
				this.byteBuffer.clear();
			if (this.bufferOutput != null)
				this.bufferOutput.clear();
			this.byteBuffer = null;
			this.bufferOutput = null;
			if (this.timer != null)
				this.timer.cancel();
		} catch (Exception localException) {
		}
	}

	public void closeChannel() {
		try {
			SelectionKey key = null;
			try {
				clear();
				if ((getId() != null) && (!getId().equals(""))) {
					synchronized (TerServer.channelHash) {
						TerServer.channelHash.remove(getId());
					}
				}
				this.channelType = "0";
				if (this.sc != null)
					key = this.sc.keyFor(this.selector);
				if (this.sc != null) {
					this.sc.close();
				}
				if (key != null) {
					key.cancel();
				}
				logger.info("SHW#关闭终端" + getId() + "的连接");

				this.channelId = null;
				this.sc = null;
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			logger.info("SHW#终端关闭异常,连接可能已关闭!");
		}
	}

	public String getUname() {
		return this.uname;
	}

	public void setUname(String uname) {
		this.uname = uname;
	}
}